<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>
        <a href="/">商品列表</a>
      </el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card class="box-card">
      <el-alert title="注意：只允许选择三级分类相关参数" type="warning" show-icon :closable="false"></el-alert>
      <!-- 步骤条 -->
      <el-steps :space="200" :active="currentIndex-0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tab栏区域 因为要搜集下面数据,所以最外层包裹了一个表单 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
        class="demo-ruleForm"
        label-position="top"
      >
        <el-tabs
          :tab-position="'left'"
          v-model="currentIndex"
          :before-leave="beforeTabsLeave"
          @tab-click="handleTabClick"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item type="number" label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number"></el-input>
            </el-form-item>
            <!-- 选择分类 -->
            <el-form-item label="商品列表" prop="goods_cat">
              <el-cascader
                style="width:100%;"
                v-model="addForm.goods_cat"
                :options="cateList"
                :props="cascaderProps"
                @change="handleCascaderChange"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              v-for="(item) in manyTabData"
              :key="item.attr_id"
              :label="item.attr_name"
              prop="attr_vals"
            >
              <!-- 复选框 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox border v-for="(el, index) in item.attr_vals" :key="index" :label="el"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item v-for="(item) in onlyTabData" :key="item.attr_id" :label="item.attr_name">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              class="upload-demo"
              :action="pictureURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="uploadSuccess"
              list-type="picture"
              :headers="headersObj"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器 -->
             <quill-editor
             ref="myQuillEditor"
             v-model="addForm.goods_introduce"
           />
            <el-button type="primary" @click="addGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <!-- 对话框 -->
      <el-dialog title="图片预览" :visible.sync="dialogVisible" width="50%">
        <span>
          <img style="width:100%" :src="urlpic" alt />
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
var deep = require('lodash')
export default {
  data () {
    return {
      // 要实现步骤条和tab区域的同步效果,就公用currentIndex,但是注意tab中会把它转成数字型的字符串,而步骤区域需要的是数字.所以要转化,减零是最方便的操作
      currentIndex: 0,
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [],
        pics: [],
        goods_introduce: '',
        attrs: []
      },
      addFormRules: {
        goods_name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
        ]
      },
      // 分类列表
      cateList: [],
      cascaderProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        checkStrictly: true
      },
      // 动态参数数据
      manyTabData: [],
      onlyTabData: [],
      // 图片上传地址
      pictureURL: 'http://127.0.0.1:8888/api/private/v1/upload',
      // 根据文档说明，给upload组件添加属性设置token
      // 因为这里图片上传用的时action，全局设置的登录拦截设置的token对他没有用
      headersObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      urlpic: '',
      dialogVisible: false
    }
  },
  mounted () {
    this.getCateList()
  },
  computed: {
    cateId () {
      return this.addForm.goods_cat.length === 3
        ? this.addForm.goods_cat[2]
        : undefined
    }
  },
  methods: {
    async getCateList () {
      const { data: res } = await this.$http.get('categories', {
        params: { type: 3 }
      })
      this.cateList = res.data
    },
    // 下拉框发生变化的时候
    handleCascaderChange () {
      // 如果选中的不是第三级，那么就清空
      if (this.addForm.goods_cat.length < 3) {
        this.addForm.goods_cat = []
      }
    },
    // Tab栏拦截，判断是否选择参数
    beforeTabsLeave (activeName, oldActiveName) {
      if (oldActiveName === '0' && this.addForm.goods_cat.length < 3) {
        this.$message.error('请选择分类')
        return false // 阻止tab切换
      }
    },
    async handleTabClick (tab) {
      if (tab.name === '1') {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: 'many' }
          }
        )
        if (res.meta.status !== 200) return this.$message.error('失败')
        res.data.forEach((item) => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
        })
        this.manyTabData = res.data
      } else if (tab.name === '2') {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: 'only' }
          }
        )
        if (res.meta.status !== 200) return this.$message.error('失败')
        this.onlyTabData = res.data
      }
    },
    // 图片上传
    handlePreview (file) {
      this.urlpic = file.response.data.url
      this.dialogVisible = true
    },
    handleRemove (file) {
      const strpic = file.response.data.tmp_path
      const index = this.addForm.pics.findIndex((item) => {
        return item.pic === strpic
      })
      console.log(index)
      this.addForm.pics.splice(index, 1)
      console.log(this.addForm.pics)
    },
    uploadSuccess (response) {
      console.log(response)
      this.addForm.pics.push({ pic: response.data.tmp_path })
      console.log(this.addForm.pics)
    },
    addGoods () {
      this.$refs.addFormRef.validate(async (valid) => {
        console.log(valid)
        if (!valid) return this.$message.error('请输入完整的值')
        // 把goods_cat转成字符串
        var form = deep.cloneDeep(this.addForm)
        form.goods_cat = form.goods_cat.join(',')
        // 处理attrs数据
        this.manyTabData.forEach((item) => {
          form.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(',')
          })
        })
        this.onlyTabData.forEach((item) => {
          form.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          })
        })
        // 发送请求添加商品
        const { data: res } = await this.$http.post('goods', form)
        if (res.meta.status !== 201) this.$message.error('创建商品失败')
        this.$message.success('创建商品成功')
        // 编程式导航跳转到列表页
        this.$router.push('/goods')
      })
    }
  }
}
</script>
<style scoped>
.el-alert {
  margin: 20px 0 30px;
}
.el-tabs {
  margin: 20px 0;
}
.el-checkbox {
  margin: 0 5px 0 0;
}
</style>
